import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";

import { GetOrganizationApplicationsByAiRole } from "../_graphql/organizations";

const useRoles = () => {
    const { graphqlFetchPlatform } = useModel("global");

    const state = useReactive({
        loading: false,
        apploading: false,
        roles: [],
        applications: [],
        selectedRole: "",
        aggregate: {},
    });

    const loadRoles = async () => {
        state.loading = true;
        let query = `query MyQuery { a: allOrganizationApplicationRoles { totalCount nodes { oarName oarDesc } } }`;
        let res = await graphqlFetchPlatform({ query, variables: {} });
        state.roles = res?.a?.nodes || [];
        state.loading = false;
    };

    useEffect(() => {
        if (state.roles.length > 0) {
            state.selectedRole = state.roles.find((item) => item.oarName === state.selectedRole)?.oarName;
            !state.selectedRole && (state.selectedRole = state.roles[0].oarName);
        }
    }, [state.roles]);

    const setSelectedRole = (data) => (state.selectedRole = data);

    const loadRoleAndChargeApplications = async (roleName) => {
        state.apploading = true;
        let res = await graphqlFetchPlatform({
            query: GetOrganizationApplicationsByAiRole,
            variables: {
                aiRole: roleName,
                isFree: false,
                aiStat: "已上架",
            },
        });
        state.applications = res?.a?.nodes || [];
        if (state.applications.length > 0) {
            state.aggregate = state.applications.reduce((prev, next) => {
                let aiSdprs = (prev.aiSdprs || 0) + parseFloat(next.aiSdpr || 0);
                let aiSpprs = (prev.aiSpprs || 0) + parseFloat(next.aiSppr || 0);
                let aiEcprs = (prev.aiEcprs || 0) + parseFloat(next.aiEcpr || 0);
                return { aiSdprs, aiSpprs, aiEcprs };
            }, []);
        } else {
            state.aggregate = {};
        }
        state.apploading = false;
    };

    return { ...state, loadRoles, setSelectedRole, loadRoleAndChargeApplications };
};

export default useRoles;
